<?php

namespace App\Http\Controllers\Api;

use App\Events\addLog;
use App\Http\Controllers\Controller;
use App\Http\Resources\AdminResource;
use App\Models\Log;
use App\Models\User;
use Illuminate\Auth\Events\Logout;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{

    /**
     * 登录
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|mixed|\Symfony\Component\HttpFoundation\Response
     */
    public function login(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'username' => 'required',
            'password' => 'required'
        ],
        [
            'username.required' => '用户名必填',
            'username.exists' => '用户名不存在',
            'password.required' => '密码必填'
        ]);


        if ($validator->fails()) {
            return response($validator->errors()->toArray(), 401);
        }
        $user = User::where('username', $request->get('username'))->first();
        if (!$user){
            return response()->json(['message'=>'用户不存在'],461);
        }
        if(!Hash::check($request->get('password'),$user->password)){
           return response()->json(['message'=>'密码错误'],461);
        }
        Auth::login($user);
        return new AdminResource($user);
    }

    public function logout(){
       event(new addLog(Auth::user(),'登出'));
    }
}
